import {PlusOutlined} from '@ant-design/icons';
import {Button, message, Input, Drawer} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {useIntl, FormattedMessage, history} from 'umi';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {ProFormGroup, ProFormSelect, ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import ProDescriptions from '@ant-design/pro-descriptions';
import ProForm from '@ant-design/pro-form'
import {getLRSInfo, getInRegs, getRegInfo, connectRemoteReg, testRemoteRegConnection,getOutRegs} from "@/services/doa/regi";
import ProCard from "@ant-design/pro-card";
import ReactFlow from "react-flow-renderer";

const RegManage = () => {


  const irsRef = useRef();
  const regRef = useRef();
  const formRef = useRef();
  const [irsInfo, setIrsInfo] = useState([])
  const [regTest, setRegTest] = useState({})
  const [ownInfo, setOwnInfo] = useState([])
  const [regInfo, setRegInfo] = useState([])

  const info = (msg) => {
    message.info(msg);
  };

  const testReg = () => {
    testRemoteRegConnection(regTest).then((response) => {
      if (response?.success && response?.data) {
        info("测试连接成功！")
      } else {
        info("测试连接失败！请确认输入地址是否正确。")
      }
    })
  }

  const updateRemoteRegs = () => {
    getOutRegs().then((response) => {
      if (response.success) {
        const regs = JSON.parse(response?.data)
        const res = []
        console.log(res)
        const level = regs.level
        for(const index in regs){
          if (regs[index].indexLevel!==0){
            res.push({doi:regs[index].id, "owner":"", address:regs[index].url, "level": regs[index].indexLevel == 2 ? "托管" : regs[index].indexLevel == 1 ? "分布式接入" : "未知"})
          }
        }
        setRegInfo(res)
      }

    })
  }

  const elements = [
    {
      id: '1',
      type: 'input', // input node
      data: { label: 'Input Node' },
      position: { x: 250, y: 25 },
    },
    // default node
    {
      id: '2',
      // you can also pass a React component as a label
      data: { label: <div>Default Node</div> },
      position: { x: 100, y: 125 },
    },
    {
      id: '3',
      type: 'output', // output node
      data: { label: 'Output Node' },
      position: { x: 250, y: 250 },
    },
    // animated edge
    { id: 'e1-2', source: '1', target: '2', animated: true },
    { id: 'e2-3', source: '2', target: '3' },
  ];


  const connectReg = (regToConn) => {
    connectRemoteReg(regToConn).then((response) => {
      if (response?.success && response?.data) {
        if (regToConn.level === "0")
          info("断开连接成功！")
        else
          info("连接成功！")
        updateRemoteRegs()
      } else {
        if (regToConn.level === "0")
          info("断开连接失败！")
        else
          info("连接失败！请确认输入地址是否正确。")
      }
    })
  }


  const doiParse = (doi) => {
    if (doi == null || doi === "")
      return ["", ""]
    return doi.split("/")
  }


  useEffect(async () => {

    await getRegInfo().then((response) => {
      if (response.success) {
        setOwnInfo(JSON.parse(response.data))
      }
    })
  }, [])

  useEffect(() => {

    getLRSInfo().then((response) => {
      if (response.success) {
        setIrsInfo([{"doi": doiParse(ownInfo?.id)[0], "owner": ownInfo?.owner, address: response.data}])
      }
    })
    updateRemoteRegs()
  }, [ownInfo])

  useEffect(() => {
    irsRef.current.reloadAndRest()
  }, [irsInfo])

  useEffect(() => {
    regRef.current.reloadAndRest()
  }, [regInfo])


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const intl = useIntl();

  const irsColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
    },
    {
      dataIndex: 'doi',
      title: 'IRS标识',
    },
    {
      dataIndex: 'owner',
      title: '所有者标识',
    },
    {
      dataIndex: 'address',
      title: '访问地址',
    }
  ];

  const regColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
    },
    {
      dataIndex: 'doi',
      title: 'Registry标识',
    },
    {
      dataIndex: 'address',
      title: '访问地址',
    },
    {
      dataIndex: 'level',
      title: '接入方式',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: (text, record, _, action) => [
        <a
          key="detail"
          onClick={() => {
            history.push({pathname: "/doa/dodetail/resolve", query: {"doi": record.doi}})
          }}
        >
          详情
        </a>,
        <a
          key="delete"
          onClick={() => {
            connectReg({"regID": record.doi, "level": "0"})
          }}
        >
          断开连接
        </a>,
      ],
    },
  ];


  return (
    <PageContainer>
      <ProTable
        headerTitle={intl.formatMessage({
          id: 'pages.regi.irsTable.title',
          defaultMessage: '当前接入的IRS服务器',
        })}
        style={{"margin-bottom": "20px"}}
        actionRef={irsRef}
        rowKey="key"
        search={false}
        pagination={false}
        toolBarRender={() => []}
        request={async (params, sort, filter) => {
          return Promise.resolve({
            data: irsInfo,
            success: true,
          });
        }}
        columns={irsColumns}
      />

      <ProCard title="接入新的Registry" style={{"margin-bottom": "20px"}}>
        <ProForm
          formRef={formRef}
          submitter={{
            searchConfig: {
              submitText: intl.formatMessage({
                id: 'pages.regi.accessReg',
                defaultMessage: '接入',
              }),
              resetText: '重置',
            },
            // 配置按钮的属性
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                display: 'none',
              },
            },
            render: (props, doms) => {
              return [
                <Button type="primary" htmlType="button" onClick={() => {
                  testReg()
                }} key="test">
                  测试连接
                </Button>,
                <Button type="primary" htmlType="button" onClick={() => {
                  connectReg(regTest)
                }} key="test">
                  接入
                </Button>,
              ];
            },
          }}
          onFinish={(values) => {
            console.log(values);
          }}
          onValuesChange={(_, values) => {
            console.log(values);
            setRegTest(values)
          }}
        >
          <ProFormGroup>
            <ProFormText width="md" name="regID" label="输入Registry地址"
                         rules={[{required: true}]}/>
            <ProFormSelect
              name="level"
              label="请选择接入Registry方式"
              valueEnum={{
                1: '接入',
                2: '托管',
              }}
              placeholder="请选择接入Registry方式"
              rules={[{required: true, message: 'Please select your access method!'}]}
            />
          </ProFormGroup>
        </ProForm>
      </ProCard>

      <ProTable
        headerTitle={intl.formatMessage({
          id: 'pages.regi.regTable.title',
          defaultMessage: '接入的Registry和Repository信息',
        })}
        style={{"margin-bottom": "20px"}}
        actionRef={regRef}
        rowKey="key"
        search={false}
        pagination={false}
        toolBarRender={() => []}
        request={async (params, sort, filter) => {
          return Promise.resolve({
            data: regInfo,
            success: true,
          });
        }}
        columns={regColumns}
      />

      <ProCard title={"注册表拓扑图"}>
        <div style={{ height: 300}}>
          <ReactFlow elements={elements} />
        </div>
      </ProCard>

    </PageContainer>
  );
};

export default RegManage;
